package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.service.RoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleMenuService.class)
@Transactional
public class RoleMenuServiceImpl implements RoleMenuService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;
    /**
     * 根据用户名获取用户角色菜单
     * @param userName
     * @return
     */
    @Override
    public List<Map<String,Object>> findRoleMenu(String userName) {
        List<Map<String,Object>> result=new ArrayList<>();
        //获取用户角色信息
        List<Role> roleList=roleMapper.findRoleByUserName(userName);
        if(roleList==null){
            return null;
        }
        //遍历角色信息获取所有角色
        for (Role role : roleList) {
            //根据每个角色查询角色所拥有的菜单
            //先获取一级菜单信息
            List<Menu> firstMenus=menuMapper.findMenuByRole(role.getKeyword(),1);
            //如果为空直接返回空
            if(firstMenus==null){
                return null;
            }
            //遍历一级菜单获取二级菜单
            for (Menu firstMenu : firstMenus) {
                Map<String, Object> firstmap = new HashMap<>();
                firstmap.put("path",firstMenu.getPath());
                firstmap.put("title",firstMenu.getName());
                firstmap.put("icon",firstMenu.getIcon());
                //获取二级菜单
                List<Menu> secondMenus=menuMapper.findMenuByParentMenuId(role.getKeyword(),firstMenu.getId());
                //二级菜单为空直接下一次循环
                if(secondMenus==null){
                    continue;
                }
                List<Map<String,Object>> secondList=new ArrayList<>();
                for (Menu secondMenu : secondMenus) {
                    //封装二级菜单数据
                    Map<String, Object> secondMap = new HashMap<>();
                    secondMap.put("path",secondMenu.getPath());
                    secondMap.put("title",secondMenu.getName());
                    secondMap.put("linkUrl",secondMenu.getLinkUrl());
                    secondMap.put("children",null);
                    secondList.add(secondMap);
                }
                firstmap.put("children",secondList);
                result.add(firstmap);
            }
        }
        return result;
    }
}
